package com.leyou.sms.mq;

import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.util.SendSms;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;
import static com.leyou.common.constants.MQConstants.QueueConstants.SMS_VERIFY_CODE_QUEUE;
@Component
public class SmsConsumer {
@Autowired
private SendSms sendSms;


    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = SMS_VERIFY_CODE_QUEUE,durable ="true" ),
                    exchange = @Exchange(name = SMS_EXCHANGE_NAME,durable = "true"),
                    key = VERIFY_CODE_KEY
            )
    })
    public void Consumer(Map<String,String> map){
        //这个方法里有异常不能跑，不然mq会判定消息没有接收到，会不停的重复发送
        if(CollectionUtils.isEmpty(map)){
            //空消息
            return;
        }
        String phone = map.get("phone");
        //正则校验手机号
        if(!RegexUtils.isPhone(phone)){
            return;
        }
        String code = map.get("code");
        //正则校验验证码
        if(!RegexUtils.isCodeValid(code)){
            return;
        }
        //发送短信验证码
        sendSms.sendVerificationCode(phone,code);

    }
}
